<?php
namespace AdminBundle\Repository;


class TaskJobSchedulesRepository extends BaseRepository
{
    public function pageQuery($_params, $page)
    {
        $sql = <<<EOF
select 
id, job_id, next_run_date, next_run_time
from task_job_schedules 
where 1=1 
EOF;
        $params = array();
        $sql .= ' ORDER BY id DESC';

        return $this->pageWithRawSql($sql, $params, $page);
    }

    /**
     * 生成需要执行的作业，并获取当前可执行的作业
     * @return bool
     * @throws \Exception
     */
    public function runnableJobs()
    {
        $sql = <<<EOF
SELECT 
    s.id,
    s.next_run_date,
    s.next_run_time,
    j.id AS jobId,
    j.name AS jobName,
    j.start_step_id,
    j.package_id AS packageId,
    j.group_id AS groupId,
    j.creator,
    d.username,
    d.password,
    d.token
FROM
    cloud_control.task_job_schedules AS s
        INNER JOIN
    cloud_control.task_jobs AS j ON s.job_id = j.id
        INNER JOIN
    cloud_control.base_group AS g ON j.group_id = g.id
        INNER JOIN
    cloud_control.base_data_source AS d ON g.data_source_id = d.id
WHERE
    s.next_run_date <= CURRENT_DATE()
        AND s.next_run_time <= CURRENT_TIME()
EOF;
        $params = array();
        $sql .= ' ORDER BY s.next_run_time';

        return $this->rawQuery($sql, $params);
    }


    /**
     * 处理当前作业的时间调度
     * @return int
     */
    public function finishScheduleJob($jobId)
    {
        $sql = <<<EOF
UPDATE task_jobs 
SET 
    is_enabled = 0
WHERE
    freq_type < 2 AND is_enabled = 1
    AND id = {$jobId} ;
EOF;
        $this->rawExecute($sql);

        $sql = <<<EOF
DELETE FROM task_job_schedules WHERE job_id = {$jobId};
EOF;
        return $this->rawExecute($sql);
    }

    /**
     * 下次作业的时间调度
     * @return int
     */
    public function nextSchedule($duration)
    {
        $sql = <<<EOF
INSERT INTO task_job_schedules(job_id,next_run_date,next_run_time)
SELECT 
    id AS job_id,CURDATE() AS next_run_date,active_start_time AS next_run_time
FROM
    task_jobs
WHERE
    active_start_date <= CURRENT_DATE()
        AND CURRENT_DATE() <= active_end_date
        AND active_start_time > DATE_ADD(CURRENT_TIME(),INTERVAL -{$duration} SECOND)        
        AND active_start_time <= CURRENT_TIME()
        AND CURRENT_TIME() <= active_end_time
        AND is_enabled = 1
        AND NOT EXISTS(SELECT * FROM task_job_schedules WHERE task_jobs.id = task_job_schedules.job_id)
EOF;
        return $this->rawExecute($sql);
    }
}
